/*关闭弹窗*/
$(function(){
    var $headImage =$('#head-image');
    var $close = $("#close");
    var $mask = $('#mask');
    var $toggle=$('#toggle');
    var $music = $('#music');
    var $word = $('#word');
    var $bigPhoto =$('#bigPhoto');
    $toggle.on('tap',function(e){
        var $this = $(this);
        var checkCase = $this.hasClass('word-text');
        if(!!checkCase){
            $this.removeClass('word-text');
            $music.show();
            $word.hide();
        }else{
            $this.addClass('word-text');
            $music.hide();
            $word.show();
        }
        e.stopPropagation();
        e.preventDefault();
        return false;
    })
    $headImage.on('tap',function(e){
        $mask.show();
        $bigPhoto.show();
        common.photoScale('.pinch-zoom');
        e.stopPropagation();
        e.preventDefault();
        return false;
    });
	$close.on('tap',function(e){
       $(this).parent().hide();
       $mask.hide();
       e.stopPropagation();
       e.preventDefault();
       return false;
    });
    $bigPhoto.on('touchmove',function(e){
        e.stopPropagation();
        e.preventDefault();
        return false;
    })
    /*通过滚动条来判断顶部*/
    var $header = $('#wrapper');
    var $endways = $('#endways');
    var $sidewards =$('#sidewards');
    var $btnToggle =$('#btn-toggle');
    var endwaysHeight = $sidewards.height();
    $(window).on("scroll",function (e) {
        if($(this).scrollTop()>=endwaysHeight){
        $header.addClass('active');
        $endways.hide();
        $sidewards.show();
        $btnToggle.addClass('btn');
    }else{
        $header.removeClass('active');
        $endways.show();
        $sidewards.hide();
        $btnToggle.removeClass('btn');
    }
    });
    /*请求后端数据*/
   	var $errorResponse = $('#errorResponse');
   	var $coverImg = $('.coverImg');
	var $music =$('#music');
	var $word =$('#word');
    var HOUSE_ID = common.getQueryString('houseId');
    if(!HOUSE_ID){
    	$errorResponse.show();
    }
    var GLOBAL_HOST = common.GLOBAL_HOST;
    var AUDIO_LIST = common.AUDIO_LIST;
    var AUDIO_LIST_PORT = GLOBAL_HOST + AUDIO_LIST;
	var LOGO_URL = common.LOGO_URL;
	var isWeiXinNavigator = common.isWeiXinNavigator();
   common.requestFormData({
   		url:AUDIO_LIST_PORT,
   		sendData:{houseId:HOUSE_ID},
   		resSuccess:function(data){
   			var data = data.res.data;
   			$coverImg.attr('src',GLOBAL_HOST+data['houseInfo']['audioPhoto']);
   			wxShareConfig(LOGO_URL,data['houseInfo']['villageName'])
   			var music = musicRender({
   				dataList:data['audios']
   			});
   			$music.html(music);
   			var word = wordRender({
   				dataList:data['words']
   			})
   			$word.html(word);
   			var house = houseInfoRender({
   				houseInfo:data['houseInfo']
   			})
   			$endways.append(house);
   			$sidewards.append(house);
			if(!isWeiXinNavigator){
				isNotWeiXin();
			}
   			common.photoScale('.pinch-zoom');
   		},
   		resFailed:function(){
   			$errorResponse.show();
   		},
   		resError:function(){
   			$errorResponse.show();
   		}
   })
document.addEventListener("WeixinJSBridgeReady", function(e) {
	var timer=setInterval(function(){
		var aList = $("audio");
		var sourceList=$("source");
		var source=sourceList.attr("src");
		if(!!source) {
			clearInterval(timer);
			$.each(aList,function(i,e){
				e.load();
			});
			playAudio(aList);
		}
	},1000)
}, false);
//解决非微信不播放的问题
function isNotWeiXin(){
	//解决非微信不播放的问题
	var audios = $('audio');
	$.each(audios,function(i,e){
		e.load();
	});
	playAudio(audios);
}
   /*微信分享调用*/
   function wxShareConfig(LOGO_URL,VILLAGE_NAME){
		var SHARE_TITLE = '【舍艺】'+VILLAGE_NAME+'语音导览'
	    wx.ready(function() { 
	        wxinit._onMenuShareTimeline({
	            title:SHARE_TITLE,
	            imgUrl:LOGO_URL
	        });
	        wxinit._onMenuShareAppMessage({
	            title:SHARE_TITLE,
	            imgUrl:LOGO_URL,
	            desc:'聆听本房源详细信息，专业解读房屋特性，提供解决方案'
	        });
	    });
	    wx.error(function (res) {//错误时调用
	        alert(res.errMsg);
	    });
	}
   /*渲染房源信息*/
	function houseInfoRender(options){
	  	var targetSelector = $(options.targetSelector);
	  	var houseInfo = options.houseInfo;
	  	var houseType ='';
	  	houseType += houseInfo['houseTypeOne']===""?"":houseInfo['houseTypeOne']+'室';
	  	houseType += houseInfo['houseTypeTwo']===""?"":houseInfo['houseTypeTwo']+'厅';
	  	houseType += houseInfo['houseTypeThree']===""?"":houseInfo['houseTypeThree']+'卫';
	  	var tempDOM = '<div class="right">'+
	  						'<p class="village">'+houseInfo['villageName']+'</p>'+
	  						'<p class="area">'+houseInfo['houseFloorArea']+'㎡</p>'+
	  						'<p class="houseType">'+houseType+'</p>'+
	  					'</div>';
	  	return tempDOM;
	}
    /*音频列表渲染*/
   function musicRender(options){
   		var dataList = options.dataList||[];
   		var arrTemp=[];
   		var top = 1.8;
	   	$.each(dataList,function(idx,ele){
	   		if(idx === 0){
	   			var tempDom = '<div class="row row-right">'+
	   							'<audio class="hide" controls preload="auto" data-duration="'+ele['duration']+'">'+
	   								'<source src="'+ele['audioPath']+'">'+
	   							'</audio>'+
	   							'<p class="content"><input type="button" class="play stoped"><span class="active">'+ele['audioName']+'</span></p>'+
	   							'<p class="progress stopedIt"></p>'+
	   						'</div>';
	   		}else if(idx % 2 == 0){
	   			var tempDom = '<div class="row row-right" style="top:'+(top*idx+0.5)+'rem">'+
	   								'<audio class="hide" controls preload="auto" data-duration="'+ele['duration']+'">'+
	   									'<source src="'+ele['audioPath']+'" type="audio/mpeg">'+
	   								'</audio>'+
	   								'<p class="content"><input type="button" class="play"><span>'+ele['audioName']+'</span></p>'+
	   								'<p class="progress"></p>'+
	   							'</div>'
	   		}else if(idx % 2 == 1){
	   			var tempDom = '<div class="row row-left" style="top:'+(top*idx+0.5)+'rem">'+
	   								'<audio class="hide" controls preload="auto" data-duration="'+ele['duration']+'">'+
	   									'<source src="'+ele['audioPath']+'" type="audio/mpeg">'+
	   								'</audio>'+
	   								'<p class="content"><input type="button" class="play"><span>'+ele['audioName']+'</span></p>'+
	   								'<p class="progress"></p>'+
	   							'</div>'
	   			
	   		}
	   		arrTemp.push(tempDom); 						
	   })
	   	return arrTemp.join("");
   }
   function wordRender(options){
   	 var dataList = options.dataList||[];
   	 var arrTemp = [];
   	 $.each(dataList, function(index,ele) {
   	 	var tempDom = '<div class="section1">'+
   	 						'<h1>'+ele['audioName']+'</h1>'+
   	 						'<p>'+ele['content'].replace(common.regWarp,'<br/>')+'</p>'+
   	 					'</div>';
   	 	arrTemp.push(tempDom);
   	 });
   	 return arrTemp.join('');
   }
   function playAudio(audios){
		var $audios = audios;
		if(isWeiXinNavigator){
			$audios[0].play();
			$audios.eq(0).siblings("p.content").children('input').removeClass('stoped').addClass("playing");
			$audios.eq(0).removeClass("stoped").addClass('playing').siblings("p.progress").removeClass('stopedIt').addClass('playingIt');
		}
		var $playBtns = $('.play');
		var counter = "";
		var startProgress = function(obj, prog, isPlay) {
			isPlay = isPlay === undefined ? true : false;
			var timefmt = function(sec) {
				var second = (sec * 1).toFixed(0),
					minute = Math.floor(second / 60),
					second = second % 60;
				if(minute < 10)
					minute = "0" + minute;
				if(second < 10)
					second = "0" + second;
				return minute + ":" + second;
			}
			var refreshProgress = function(audio, prog) {
				var duration = !!audio.duration ? audio.duration : "";
				var current = timefmt(audio.currentTime),
				total = timefmt(duration);
				//非微信情况下，按照数据库读取的总时长进行判断
				total = !!isWeiXinNavigator ? timefmt(duration) : timefmt(Number($(audio).attr('data-duration')));
				if(current === total){
					clearInterval(counter);
					current = '00:00';
					var index = $audios.index(obj) ;
					var indexPlus = index + 1;
					var len = $audios.length;
					$('.play').removeClass('playing').removeClass('stoped').next().removeClass('active').end().parent().next().removeClass('playingIt').removeClass("stopedIt");
					$audios.removeClass('active');
					if(indexPlus < len){
						$audios[indexPlus].play();
						$audios.eq(indexPlus).siblings("p.content").children('input').removeClass('stoped').addClass("playing").next().addClass('active');
						$audios.eq(indexPlus).removeClass("stoped").addClass('playing').siblings("p.progress").removeClass('stopedIt').addClass('playingIt');
					}
				}
				prog.text(current + " / " + total);
			}
			if(isPlay) {
				clearInterval(counter)
				counter = setInterval(function(a, b, c) {
					refreshProgress(a, b, c);
				}, 1000, obj, prog);
			} 
			 $(obj).off("canplay").on("canplay", function() {
			 	refreshProgress(this, prog);
			 });
		}
		$playBtns.off('click').on('click', function(e) {
			clearInterval(counter)
			var audio = $(this).parent().siblings('audio');
			if($(this).hasClass('playing')) {
				$(this).removeClass('playing').addClass("stoped").next().removeClass('active').end().parent().next().removeClass('playingIt');
				$(this).next().addClass('active').end().parent().next().addClass('stopedIt');
				audio[0].pause();
				audio.removeClass('active');
			} else if($(this).hasClass('stoped')) {
				$(this).removeClass("stoped").addClass('playing').next().addClass('active').end().parent().next().removeClass('stopedIt').addClass('playingIt');
				audio[0].play();
				audio.addClass('active');
			} else {
				$('.play').removeClass('playing').removeClass('stoped').next().removeClass('active').end().parent().next().removeClass('playingIt').removeClass("stopedIt");
				$(this).removeClass("stoped").addClass('playing').next().addClass('active').end().parent().next().addClass('playingIt');
				$audios.removeClass('active');
				audio.addClass('active');
				$.each($audios, function(idx, ele) {
					if($(ele).hasClass('active')) {} else {
						ele.load();
					}
				})
				audio[0].play();
			}
			e.preventDefault();
			return false;
		});
		$('audio').map(function(i, audio) {
			startProgress(this, $(audio).siblings('p.progress'), false);
		});
		$('audio').on('playing', function(e) {
			startProgress(this, $(this).siblings('p.progress'));
		});
   }

})

